package com.group.three.controller.buyerController;

import com.group.three.entity.dto.UserPwdLoginInfoDto;
import com.group.three.redis.JedisDao;
import com.group.three.service.impl.LiMemberServiceImpl;
import com.group.three.untils.JwtUtils;
import com.group.three.vo.JsonResult;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;



@Controller
@Slf4j
@RequestMapping("/buyer/passport")
@CrossOrigin
@Api(value = "pc商城保护模块" ,tags = {"1.安全"})
public class PassportController {

    @Autowired
    private LiMemberServiceImpl liMemberService;
    @Autowired
    private JedisDao jedisDao ;

    @ResponseBody
    @PostMapping("/member/smsLogin")
    @ApiOperation(value = "用户账号密码登录",notes = "根据username登录")
    public JsonResult smsLogin(String username, String password) {
        log.info("接受到用户名={}的登录请求", username);
        UserPwdLoginInfoDto loginInfoDto = liMemberService.pwdLoginInfoDto(username, password);
        //密码不对
        if (null == loginInfoDto){
            return new JsonResult<>("400","账号或者密码不正确");
        }
        //这里还需要生产两个token,accessToken和 refreshToken
        Map<String, Object> loginData = new HashMap<>();
        String accessToken = JwtUtils.encodeToJwt(loginInfoDto);
        String refreshToken = UUID.randomUUID().toString().replaceAll("-", "");
        loginData.put("accessToken", accessToken);
        loginData.put("refreshToken",refreshToken);


        //将两个token 存入 redis中
        jedisDao.setex("accessToken_"+username,300,accessToken);//300秒过期
        jedisDao.setex("refreshToken_"+username,60*60*12,refreshToken);//12小时过期


        //把用户信息给前端
        loginData.put("result",loginInfoDto);
        return new JsonResult<>(loginData);
    }


    /**
     * 退出登录
     * @return
     */
    @PostMapping("/member/logout")
    @ResponseBody
    @ApiOperation(value = "用户退出逻辑(暂未实现)",notes = "删除redis中token")
    public JsonResult logOut(){
        //删除 token
        return new JsonResult<>();
    }
}
